package com.example.myapplication.utils

import android.content.Intent
import android.os.Build
import android.text.Html
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.URLSpan
import android.view.View
import android.widget.TextView
import androidx.annotation.ColorInt
import com.example.myapplication.ui.WebActivity


object RichTextUtils {
    /**
     * 设置富文本并自定义链接样式
     * @param textView 目标TextView
     * @param text
     * @param linkColor
     * @param underline
     */
    fun setRichTextWithCustomLink(
        textView: TextView, text: String?,
        @ColorInt linkColor: Long = 0xFF578FF7, underline: Boolean = false
    ) {
        val text = text ?: ""
        val spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Html.fromHtml(text, Html.FROM_HTML_MODE_COMPACT)
        } else {
            Html.fromHtml(text)
        }
        val builder = SpannableStringBuilder(spanned)

        val urlSpans = builder.getSpans<URLSpan?>(0, builder.length, URLSpan::class.java)
        for (span in urlSpans) {
            val start = builder.getSpanStart(span)
            val end = builder.getSpanEnd(span)
            builder.removeSpan(span)
            builder.setSpan(
                CustomClickableSpan(span.url, linkColor.toInt(), underline),
                start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }

        textView.apply {
            this.text = builder
            movementMethod = LinkMovementMethod.getInstance()
            setLinkTextColor(linkColor.toInt())
        }
    }

    class CustomClickableSpan internal constructor(
        private val url: String?,
        private val color: Int,
        private val underline: Boolean
    ) : ClickableSpan() {
        override fun onClick(widget: View) {
            val intent = Intent(widget.context, WebActivity::class.java).apply {
                putExtra("url", url)
            }
            widget.context.startActivity(intent)
        }

        override fun updateDrawState(ds: TextPaint) {
            ds.clearShadowLayer()
            ds.color = color
            ds.isUnderlineText = underline
        }
    }
}